<?php
// ### AclAssistant : Node
class Action_Admin_InitDB extends RL_Handler
{
	// на входе инсталлер - экземпляр интерфейса store
	private function CreateItemStructures( $o )
	{
		$struct = array();
		$general_struct = array();

		// соберем отдельную структуру для каждого итема и общую для ленты всех сообщений
		foreach ($this->ctx->doctypes as $dt_name => $doctype) {

			foreach ($doctype['fields'] as $field_name=>$field_config) {

				if (!isset($field_config['db_name'])) {
					continue;
					}

				if (isset($field_config['db_size'])) {
					$struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ][ 'size' ] = $field_config['db_size'];
					$general_struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ][ 'size' ] = $field_config['db_size'];
				} else {
					$struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ] = NULL;
					$general_struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ] = NULL;
				}

				if (isset($field_config["validator_params"]["not_empty"]) == 0) {
					$struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ]["canbenull"] = 1;
					$general_struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ]["canbenull"] = 1;
				}

				if (array_key_exists("db_default", $field_config)) {
					$struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ]["default"] = $field_config["db_default"];
					$general_struct['fields'][ $field_config['db_name'] ][ $field_config['db_type'] ]["default"] = $field_config["db_default"];
				}

			}
			//$struct['fields']['date']['datetime']=NULL;
			//$o->createClass( $dt_name, $struct );
			//unset( $struct );

		}

		// определим ленту всех сообщений
		//$general_struct['fields']['date']['datetime']=NULL;
		//$o->createClass( 'allfeed', $general_struct );

	}

	private function acl_ddl_queries()
	{
		$this->ctx->db->Query("DROP TABLE `events_stack`");
		$sql = "	CREATE TABLE `events_stack` (
  		`uid` int(10) unsigned NOT NULL auto_increment,
  		`unixmark` int(10) unsigned NOT NULL,
  		`type` varchar(40) default NULL,
  		`openid` varchar(255) default NULL,
  		`oid` int(10) unsigned default NULL,
  		PRIMARY KEY  (`uid`),
  		KEY `unixmark`(`unixmark`)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
		$this->ctx->db->Query( $sql );

		$this->ctx->db->Query("DROP TABLE `t_rssfeedsnapshots`");
		$sql = "CREATE TABLE `t_rssfeedsnapshots` (
		  `oid` int(11) NOT NULL auto_increment,
		  `rssfeed_list_oid` int(11) NOT NULL,
		  `hash` varchar(33) collate utf8_bin NOT NULL,
		  PRIMARY KEY  (`oid`),
		  KEY `class_rssfeedsnapshots_0` (`rssfeed_list_oid`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin";
		$this->ctx->db->Query( $sql );

		$this->ctx->db->Query("DROP TABLE `t_acl_list`");
		$sql = "CREATE TABLE `t_acl_list` (
		  `id` int(11) NOT NULL auto_increment,
		  `id_subject` int(11) NOT NULL,
		  `comment` varchar(50) collate utf8_bin NOT NULL,
		  `type` varchar(1) collate utf8_bin NOT NULL,
		  `action` varchar(35) collate utf8_bin NOT NULL,
		  `opt` varchar(1) collate utf8_bin NOT NULL,
		  `id_acl_tree` int(11) NOT NULL,
		  PRIMARY KEY  (`id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Acl Lists for objects in acl_tree'";

		$this->ctx->db->Query( $sql );

		$this->ctx->db->Query("DROP TABLE `t_acl_tree`");
		$sql = "CREATE TABLE `t_acl_tree` (
		  `id` int(11) NOT NULL auto_increment,
		  `id_object` int(11) NOT NULL,
		  `parent_id` int(11) NOT NULL,
		  `lft` int(11) NOT NULL,
		  `rgt` int(11) NOT NULL,
		  `_comment` varchar(50) collate utf8_bin NOT NULL,
		  `is_deleted` tinyint(1) DEFAULT '0' NOT NULL,
		  PRIMARY KEY  (`id`),
		  UNIQUE KEY `unique1` (`id_object`,`parent_id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Acl tree of objects'";

		$this->ctx->db->Query( $sql );

		$this->ctx->db->Query("DROP TABLE `t_subject_relations`");
		$sql = "CREATE TABLE `t_subject_relations` (
		  `id` int(11) NOT NULL auto_increment,
		  `parent_id` int(11) NOT NULL,
		  `lft` int(11) NOT NULL,
		  `rgt` int(11) NOT NULL,
		  `comment` varchar(30) collate utf8_bin NOT NULL default '',
		  `var` varchar(15) collate utf8_bin NOT NULL default '',
		  `id_object` int(11) NOT NULL COMMENT 'entity storage identifier',
		  PRIMARY KEY  (`id`),
		  KEY `id_obj` (`id_object`),
		  KEY `pid+id` (`parent_id`,`id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin";

		$this->ctx->db->Query($sql);

	}
	// создать таблицы для движка поиска
	private function se_ddl_queries ()
	{
		$sql = <<<EOD
CREATE TABLE IF NOT EXISTS `se_indexed` (
  `oid` int(10) unsigned NOT NULL,
  `parent_oid` int(10) unsigned NOT NULL,
  `md5_crc` varchar(32) collate utf8_bin NOT NULL,
  PRIMARY KEY  (`oid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `se_words` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(80) collate utf8_bin NOT NULL,
  `group_id` mediumint(6) unsigned NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `word` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `se_x` (
  `word_id` int(10) unsigned NOT NULL default '0',
  `oid` int(10) unsigned NOT NULL default '0',
  `rel` tinyint(3) unsigned NOT NULL default '0',
  KEY `word_id` (`word_id`),
  KEY `oid` (`oid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `se_pre_words` (
  `word` varchar(27) collate utf8_bin NOT NULL,
  `group_id` mediumint(6) unsigned NOT NULL default '0',
  KEY `word` (`word`),
  KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin PACK_KEYS=1;

ALTER TABLE `se_x` ADD `title` TINYINT( 1 ) UNSIGNED NOT NULL ;
ALTER TABLE `se_x` ADD INDEX ( `title` ) ;
EOD;

		foreach (array_filter(explode (';', $sql)) as $query) {
			$this->ctx->db->Query( $query );
		}
	} // end of method se_ddl_queries

	public function process ()
	{
		// HACK : 2008-02-12 : lucky
		// простая аутентификация.
		if (!isset($_GET['digest']) || $_GET['digest'] !== $this->rh->project_key) return; // 404

		$this->installer = $this->ctx->store->iface('StoreInstaller');
		$this->installer->createDefaultSchema();
		//$this->CreateItemStructures( $this->installer );
		// установить все
		$this->installer->purge();
		$this->installer->install();
		//$this->installer->clean();

		$this->acl_ddl_queries();
		$this->se_ddl_queries();

		$db = $this->ctx->db;
		$prefix = $db->db_prefix;
		// отношение tag -> какой-то объект
		$db->Query("DROP TABLE `{$prefix}tag_subject`");
		$sql =   "CREATE TABLE `{$prefix}tag_subject` (
		  `tag_oid` int(11) NOT NULL,
		  `subject_oid` int(11) NOT NULL,
		  PRIMARY KEY  (`tag_oid`, `subject_oid`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Acl Lists for objects in acl_tree'";
		$db->Query( $sql );

		// отношение item 1>* автор
		$db->Query("DROP TABLE `{$prefix}item_author`");
		$sql =   "CREATE TABLE `{$prefix}item_author` (
		  `item_oid` int(11) NOT NULL,
		  `author_oid` int(11) NOT NULL,
		  PRIMARY KEY  (`item_oid`, `author_oid`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Item to Author relation'";
		$db->Query( $sql );

		// visit -- считалка посещений
		$db->Query("DROP TABLE `{$prefix}visit`");
		$sql =   "CREATE TABLE `{$prefix}visit` (
			`who_oid` int(11) NOT NULL,
			`what_oid` int(11) NOT NULL,
			`y` int(11) NOT NULL,
			`m` int(11) NOT NULL,
			`d` int(11) NOT NULL,
			`ts` int(11) NOT NULL,
			`visit_count` int(11) NOT NULL,
			PRIMARY KEY  (`who_oid`,`what_oid`,`y`,`m`,`d`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin";
		$db->Query( $sql );

		$aa = $this->module->aa;
		$this->ctx->mm->setAclAssistant($aa);
		$this->ctx->mm->getModel("Node", "a")->CreateNode();

		if (!$this->ctx->db->isErrorInTransaction()) {
			$view = 'Ok';
		} else {
			$view = 'Failed data insertion. See mysql query log.';
			}

		$this->rh->response->setContent($view);
	} // end of function execute

}

